﻿using CPPEI.BD.VMTool.Datas;
using CPPEI.BD.VMTool.Until;
using CPPEI.BD.VMTool.Untils;
using CPPEI.BD.VMTool.Views;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;

namespace CPPEI.BD.VMTool
{
    /// <summary>
    /// VMToolWindow.xaml 的交互逻辑
    /// </summary>
    public partial class VMToolWindow : Window
    {
        private static List<Item> _listVideoSource;

        private static List<Canvas> _ListVideos = new List<Canvas>();

        private static Grid _selectGrid;

        private static bool _isFirstLoad;

        private static bool _isShowPopup;

        private static Canvas _isSelectedCanvas;

        private static Canvas _selectedMatrixCanvas;

        private static bool _isExChange;

        private static bool isOrderBy;
        
         private static bool _isOrderBy = true;

         private static bool isFrequency;

         private static bool _isFrequency = true;

         private static bool _selectedRadioButtonSolution = true;

         private static bool _selectedRadioButtonItem;

         private static bool _isDeleteSolution;
        
        /// <summary>
        /// 拖动的区域
        /// </summary>
        private FrameworkElement _dragScope;
        /// <summary>
        /// 用于显示鼠标跟随效果的装饰器
        /// </summary>
        private DragAdorner _adorner;
        /// <summary>
        /// 用于呈现DragAdorner的图画
        /// </summary>
        private AdornerLayer _layer;

        private Visual _dragScopeasVisual;


        private static int _numberCount;
        public VMToolWindow()
        {
            InitializeComponent();
            //第一次加载创建目录
            CreateConfigPath();
            this.Loaded += VMToolWindow_Loaded;
            this.Closed += VMToolWindow_Closed;

        }

        void VMToolWindow_Closed(object sender, EventArgs e)
        {
            UpdateLastMatrixSource();
        }

        private void CreateConfigPath()
        {
            string activeDir = string.Format(@"{0}\\coolzon\\tools\\vmtool\\V{1}",
            Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData),
            typeof(VMSolutionUntil).Assembly.GetName().Version.ToString(3));
            System.IO.DirectoryInfo di = new System.IO.DirectoryInfo(activeDir);
            di.Create();
        }
        void VMToolWindow_Loaded(object sender, RoutedEventArgs e)
        {
          
            LoadVideoMatrix();
            LoadVideoSource(null);
            LoadSorts();
            LoadLastMatrixSource();
            LoadSolutionConfig(null);
        }

        private void MenuItem_Click_1(object sender, RoutedEventArgs e)
        {
            string state = (sender as MenuItem).Header.ToString();
            _ctlTxtBlockState.Content = state;
            MenuItem menuItem = sender as MenuItem;

        }

        /// <summary>
        /// 加载视频矩阵
        /// </summary>
        private void LoadVideoMatrix()
        {
            List<VideoMatrixItem> listVideos = VMSolutionUntil.GetListVideoMatrixSource(VMSolutionUntil.GetVideoMatrixFilePath(), "VideoMatrix");
            if (listVideos != null)
            {

                _ctlWrapMatrixs.Children.Clear();
                _ctlStackPanleMatrixs.Children.Clear();
                _ctlPopupVideo.DataContext = listVideos;
                foreach (VideoMatrixItem item in listVideos)
                {
                    Canvas matrixCanvas = new Canvas();
                    matrixCanvas.AllowDrop = true;
                    matrixCanvas.Drop += matrixCanvas_Drop;
                    matrixCanvas.DragOver += matrixCanvas_DragOver;

                    matrixCanvas.Height = this.ActualHeight * 0.15d;
                    matrixCanvas.Width = this.ActualWidth * 0.154d;
                    matrixCanvas.Margin = new Thickness(5);
                    Rectangle matrixRectangle = new Rectangle();
                    matrixRectangle.Width = this.ActualWidth * 0.154d;
                    matrixRectangle.Height = this.ActualHeight * 0.15d;
                    ImageBrush rectangleBrush = new ImageBrush();


                    rectangleBrush.ImageSource = new BitmapImage(new Uri("pack://application:,,,/CPPEI.BD.VMTool;component/Images/top2mk.png", UriKind.Absolute));
                    matrixRectangle.Fill = rectangleBrush;

                    matrixCanvas.Children.Add(matrixRectangle);
                    Label videoLabel = new Label();
                    videoLabel.Foreground = new SolidColorBrush(Colors.White);
                    videoLabel.FontSize = 20;
                    videoLabel.HorizontalContentAlignment = System.Windows.HorizontalAlignment.Center;
                    videoLabel.VerticalContentAlignment = System.Windows.VerticalAlignment.Bottom;
                    videoLabel.Width = this.ActualWidth * 0.154d;
                    videoLabel.Height = this.ActualHeight * 0.15d;
                    videoLabel.Content = item.Caption;
                    matrixCanvas.DataContext = item;
                    matrixCanvas.Children.Add(videoLabel);
                    // matrixCanvas.Loaded += matrixCanvas_Loaded;


                    Button btn = new Button();
                    btn.Height = 44;
                    btn.Click += btn_Click;
                    btn.DataContext = item;
                    btn.Content = item.Caption;
                    _ctlStackPanleMatrixs.Children.Add(btn);
                    //_ctlSelectedStackPanleMatrixs.Children.Add(btn);
                    _ctlWrapMatrixs.Children.Add(matrixCanvas);
                }
            }
            else
            {
                _ctlWrapMatrixs.Children.Clear();
            }
        }

        /// <summary>
        /// 加载最后一次矩阵上的视频源信息
        /// </summary>
        private void LoadLastMatrixSource()
        {
            List<Mapping> mappings = VMSolutionUntil.GetLastMatrixSource();
            if (mappings != null && mappings.Count > 0)
            {
                foreach (Mapping map in mappings)
                {
                    foreach (UIElement ui in _ctlWrapMatrixs.Children)
                    {
                        Canvas matrixCanvas = ui as Canvas;
                        VideoMatrixItem matrixItem = matrixCanvas.DataContext as VideoMatrixItem;
                        if (matrixItem.Id == map.VideoMatrixId)
                        {
                            //移除现有的视频源，加载新的视频源
                            //if (matrixCanvas.Children.Count > 2 && matrixCanvas.Children[2] != null)
                            //{
                            //    int count = matrixCanvas.Children.Count;

                            //    for (int i = 0; i < count - 2; i++)
                            //    {
                            //        matrixCanvas.Children.RemoveAt(2);
                            //    }
                            //}
                            if (_ListVideos != null && _ListVideos.Count > 0)
                            {
                                foreach (Canvas videoCanvas in _ListVideos)
                                {
                                    if ((videoCanvas.DataContext as Item).Id == map.VideoSourceId)
                                    {
                                        string xaml = System.Windows.Markup.XamlWriter.Save(videoCanvas);
                                        Canvas nCanvas = System.Windows.Markup.XamlReader.Parse(xaml) as Canvas;
                                        nCanvas.DataContext = videoCanvas.DataContext as Item;
                                        //nCanvas.MouseRightButtonDown += videoCanvas_MouseRightButtonDown;
                                        nCanvas.PreviewMouseMove += nCanvas_PreviewMouseMove;
                                        nCanvas.MouseLeftButtonUp += onCanvas_MouseLeftButtonUp;
                                        Canvas.SetLeft(nCanvas, (this.ActualWidth * 0.154d - 132) / 2);
                                        Canvas.SetTop(nCanvas, (this.ActualHeight * 0.15 - 85) / 2);
                                        matrixCanvas.Children.Add(nCanvas);

                                        break;
                                    }
                                }
                            }
                            break;
                        }
                    }
                }
            }
        }

        /// <summary>
        /// 更新最后一次矩阵上的视频源信息
        /// </summary>
        private void UpdateLastMatrixSource()
        {
            List<Mapping> lastMapping = new List<Mapping>();
            foreach (Canvas child in this._ctlWrapMatrixs.Children)
            {
                if (child.DataContext != null)
                {
                    VideoMatrixItem matrixItem = child.DataContext as VideoMatrixItem;
                    Mapping mapping = new Mapping();
                    mapping.VideoMatrixId = matrixItem.Id;
                    if (child.Children.Count > 2)
                    {
                        Canvas canvas = child.Children[2] as Canvas;
                        if (canvas != null && canvas.DataContext != null)
                        {
                            Item videoItem = canvas.DataContext as Item;
                            mapping.VideoSourceId = videoItem.Id;
                            lastMapping.Add(mapping);
                        }
                    }
                }

            }

            VMSolutionUntil.UpdateLastMatrixSource(lastMapping);
        }

        void btn_Click(object sender, RoutedEventArgs e)
        {
            Button button = sender as Button;
            VideoMatrixItem item = button.DataContext as VideoMatrixItem;
            if (_isSelectedCanvas != null)
            {

                foreach (UIElement ui in _ctlWrapMatrixs.Children)
                {
                    Canvas matrixCanvas = ui as Canvas;
                    VideoMatrixItem matrixItem = matrixCanvas.DataContext as VideoMatrixItem;
                    if (matrixItem.Id == item.Id)
                    {
                        //移除现有的视频源，加载新的视频源
                        if (matrixCanvas.Children.Count > 2 && matrixCanvas.Children[2] != null)
                        {
                            int count = matrixCanvas.Children.Count;

                            for (int i = 0; i < count - 2; i++)
                            {
                                matrixCanvas.Children.RemoveAt(2);
                            }
                        }
                        string xaml = System.Windows.Markup.XamlWriter.Save(_isSelectedCanvas);
                        Canvas nCanvas = System.Windows.Markup.XamlReader.Parse(xaml) as Canvas;
                        nCanvas.DataContext = _isSelectedCanvas.DataContext as Item;
                        //nCanvas.MouseRightButtonDown += videoCanvas_MouseRightButtonDown;
                        nCanvas.PreviewMouseMove += nCanvas_PreviewMouseMove;
                        nCanvas.MouseLeftButtonUp += onCanvas_MouseLeftButtonUp;
                        Canvas.SetLeft(nCanvas, (this.ActualWidth * 0.154d - 132) / 2);
                        Canvas.SetTop(nCanvas, (this.ActualHeight * 0.15 - 85) / 2);
                        matrixCanvas.Children.Add(nCanvas);

                        SendToTarget(_isSelectedCanvas.DataContext as Item, matrixCanvas.DataContext as VideoMatrixItem);

                    }
                }
            }
            _ctlPopupVideo.IsOpen = false;
        }

        void nCanvas_PreviewMouseMove(object sender, MouseEventArgs e)
        {
            if (e.LeftButton == MouseButtonState.Pressed && !_isShowPopup)
            {
                _isExChange = true;
                this.StartDrag(sender, e);
            }
        }




        private void SendToAgent(Solution solution)
        {

            string targetIP = System.Configuration.ConfigurationManager.AppSettings["TargetIP"];
            int targetPort = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["TargetPort"]);

            // 发送到agent程序，让agent程序转发
            Untils.VMAgentUtil.SendToAgent(targetIP, targetPort, solution);
        }

        private void SendToTarget(Item selectedCanvasItem, VideoMatrixItem videoMatrixItem)
        {
            if (selectedCanvasItem != null)
            {
                string xmlString = string.Empty;
                if (selectedCanvasItem.Type == "VideoMatrix")
                {
                    //发送视频切换指令
                    Solution solution = new Solution();
                    solution.Mapping = new List<Mapping>();
                    Mapping mapping = new Mapping();
                    mapping.VideoMatrixId = videoMatrixItem.Id;
                    mapping.VideoSourceId = selectedCanvasItem.Id;
                    solution.Mapping.Add(mapping);
                    SendToAgent(solution);
                    xmlString = string.Format("<Int Value=\"{0}\"/>", videoMatrixItem.CameraId);
                }
                else
                {
                    xmlString = string.Format("<Int Value=\"{0}\"/>", selectedCanvasItem.CameraId);
                }

                string s_apiServiceIP = string.Empty;
                int s_apiServicePort = 0;
                try
                {

                    //string xmlString = string.Format("<Int Value=\"{0}\"/>", videoMatrixItem.CameraId);
                    s_apiServiceIP = System.Configuration.ConfigurationManager.AppSettings["ApiServiceIP"];
                    s_apiServicePort = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["ApiServicePort"]);
                    ApiServiceUtil.SendToApiService(videoMatrixItem.PartName, "CameraID", xmlString);
                    CPPEI.Coolzon.Common.Logger.Debug("发送监控切换数据到API服务，partName:{0},propertyName:{1},xmlString:{2}",
                 videoMatrixItem.PartName,
                 "CameraID",
                 xmlString);

                }
                catch (Exception ex)
                {
                    CPPEI.Coolzon.Common.Logger.Debug("发送监控切换数据到API服务:{4}:{5}，数据：partName:{0},propertyName:{1},xmlString:{2},出现错误:{3}",
               videoMatrixItem.PartName,
               "CameraID",
               xmlString,
               ex.ToString(),
               s_apiServiceIP,
               s_apiServicePort
               );
                }
                finally
                {
                    //更新视频信号使用次数
                   selectedCanvasItem.Clicks = selectedCanvasItem.Clicks + 1;
                    VMSolutionUntil.UpdateItem(selectedCanvasItem, VMSolutionUntil.GetVideoSourceFilePath());
                }
            }
        }


        private void LoadSolutionConfig(List<Datas.Solution> listSolution)
        {
            if (listSolution == null)
            {
                if (VMSolutionUntil.GetAllSolution() != null)
                {
                    listSolution = VMSolutionUntil.GetAllSolution();
                    _numberCount = listSolution.Count;
                }
            }
            if (listSolution != null)
            {
                _numberCount = VMSolutionUntil.GetAllSolution().Count;
                _ctlWplSolutions.Children.Clear();
                for (int i = 0; i < listSolution.Count; i++)
                {
                    Grid solutionGrid = new Grid();
                    //ImageBrush imageBrush = new ImageBrush();
                    //imageBrush.ImageSource = new BitmapImage(new Uri("pack://application:,,,/CPPEI.BD.VMTool;component/Images/fa.png", UriKind.Absolute));
                    //solutionGrid.Background = imageBrush;
                    solutionGrid.Margin = new Thickness(2);
                    solutionGrid.Tag = listSolution[i].Number.ToString();
                    solutionGrid.Width = 136;
                    solutionGrid.Height = 79;
                    if (_selectGrid != null && listSolution[i].Number.ToString() == _selectGrid.Tag.ToString())
                    {
                        solutionGrid.Style = (Style)Window.Resources["selectSolutionButton"];
                    }
                    else
                    {
                        solutionGrid.Style = (Style)Window.Resources["solutionButton"];
                    }
                    solutionGrid.DataContext = listSolution[i];
                    solutionGrid.MouseLeftButtonDown += solutionButton_Click;
                    solutionGrid.MouseRightButtonUp += solutionGrid_MouseRightButtonDown;
                    TextBlock captionTextBlock = new TextBlock();
                    captionTextBlock.FontSize = 14;
                    captionTextBlock.Foreground = new SolidColorBrush(Colors.Black);
                    captionTextBlock.HorizontalAlignment = System.Windows.HorizontalAlignment.Center;
                    captionTextBlock.VerticalAlignment = System.Windows.VerticalAlignment.Center;
                    captionTextBlock.Text = listSolution[i].Name; ;
                    solutionGrid.Children.Add(captionTextBlock);

                    Grid grid = new Grid();
                    grid.Margin = new Thickness(-10);
                    grid.Width = 110;
                    grid.Height = 65;

                    TextBlock ellipseTextBlock = new TextBlock();
                    ellipseTextBlock.VerticalAlignment = System.Windows.VerticalAlignment.Bottom;
                    ellipseTextBlock.HorizontalAlignment = System.Windows.HorizontalAlignment.Right;
                    ellipseTextBlock.Foreground = new SolidColorBrush(Colors.White);
                    ellipseTextBlock.Margin = new Thickness(3, 0, 3, 0);
                    ellipseTextBlock.Text = (i + 1).ToString();
                    ellipseTextBlock.FontSize = 12;

                    Ellipse ellipse = new Ellipse();
                    ellipse.Fill = new SolidColorBrush(Colors.Red);
                    ellipse.Width = 14;
                    ellipse.Height = 14;
                    ellipse.VerticalAlignment = System.Windows.VerticalAlignment.Bottom;
                    ellipse.HorizontalAlignment = System.Windows.HorizontalAlignment.Right;
                    grid.Children.Add(ellipse);
                    grid.Children.Add(ellipseTextBlock);
                    solutionGrid.Children.Add(grid);
                    _ctlWplSolutions.Children.Add(solutionGrid);

                }

            }
            else
            {
                _ctlWplSolutions.Children.Clear();
            }
        }

        void solutionGrid_MouseRightButtonDown(object sender, MouseButtonEventArgs e)
        {
            _isDeleteSolution = true;
            _selectGrid = sender as Grid;
            _ctlPopupSolution.Placement = PlacementMode.Mouse;
            _ctlPopupSolution.IsOpen = true;
        }



        /// <summary>
        /// 加载视频信息
        /// </summary>
        private void LoadVideoSource(List<Item> listVideos)
        {
            if (listVideos == null)
            {
                _isFirstLoad = true;
                _listVideoSource = VMSolutionUntil.GetListVideoSource(VMSolutionUntil.GetVideoSourceFilePath(), "VideoSource");
            }
            else
            {
                _listVideoSource = listVideos;
            }
            if (_listVideoSource != null)
            {
                _ctlWrapPanelVideo.Children.Clear();

                for (int i = 0; i < _listVideoSource.Count; i++)
                {

                    Canvas videoCanvas = new Canvas();

                    videoCanvas.PreviewMouseMove += videoCanvas_PreviewMouseMove;
                    videoCanvas.MouseLeftButtonUp += videoCanvas_MouseLeftButtonUp;
                    videoCanvas.Height = 79;
                    videoCanvas.Width = 140;
                    videoCanvas.Margin = new Thickness(2);

                    Rectangle videoRectangle = new Rectangle();

                    videoRectangle.Width = 140;
                    videoRectangle.Height = 79;
                    ImageBrush imageBrush = new ImageBrush();

                    if (_listVideoSource[i].Type == "Video")
                    {
                        imageBrush.ImageSource = new BitmapImage(new Uri("pack://application:,,,/CPPEI.BD.VMTool;component/Images/signal2.png", UriKind.Absolute));

                    }
                    else
                    {
                        imageBrush.ImageSource = new BitmapImage(new Uri("pack://application:,,,/CPPEI.BD.VMTool;component/Images/signal.png", UriKind.Absolute));
                    }
                    videoRectangle.Fill = imageBrush;

                    videoCanvas.Children.Add(videoRectangle);
                    Label videoLabel = new Label();
                    videoLabel.FontSize = 14;
                    videoLabel.Foreground = new SolidColorBrush(Colors.Black);
                    videoLabel.HorizontalContentAlignment = System.Windows.HorizontalAlignment.Center;
                    videoLabel.VerticalContentAlignment = System.Windows.VerticalAlignment.Center;
                    videoLabel.Width = 140;
                    videoLabel.Height = 79;
                    videoLabel.Content = _listVideoSource[i].Caption;
                    videoCanvas.DataContext = _listVideoSource[i];
                    videoCanvas.Children.Add(videoLabel);

                    Grid grid = new Grid();

                    grid.Margin = new Thickness(-12);
                    grid.Width = 140;
                    grid.Height = 79;

                    TextBlock ellipseTextBlock = new TextBlock();
                    ellipseTextBlock.VerticalAlignment = System.Windows.VerticalAlignment.Bottom;
                    ellipseTextBlock.HorizontalAlignment = System.Windows.HorizontalAlignment.Right;
                    ellipseTextBlock.Foreground = new SolidColorBrush(Colors.White);
                    ellipseTextBlock.Margin = new Thickness(3, 0, 3, 0);
                    ellipseTextBlock.FontSize = 12;
                    ellipseTextBlock.Text = (i + 1).ToString();

                    Ellipse ellipse = new Ellipse();
                    ellipse.Fill = new SolidColorBrush(Colors.Red);
                    ellipse.Width = 14;
                    ellipse.Height = 14;
                    ellipse.VerticalAlignment = System.Windows.VerticalAlignment.Bottom;
                    ellipse.HorizontalAlignment = System.Windows.HorizontalAlignment.Right;
                    grid.Children.Add(ellipse);
                    grid.Children.Add(ellipseTextBlock);
                    videoCanvas.Children.Add(grid);
                    if (_isFirstLoad)
                    {
                        _ListVideos.Add(videoCanvas);
                    }


                    _ctlPopupVideo.PlacementTarget = videoCanvas;

                    _ctlPopupVideo.Closed += _ctlPopupVideo_Closed;

                    _ctlWrapPanelVideo.Children.Add(videoCanvas);
                    //_ctlWrapPanelVideo.Children.Add(popupMatrix);
                }

            }
            else
            {
                _ctlWrapPanelVideo.Children.Clear();
            }
        }

        void _ctlPopupVideo_Closed(object sender, EventArgs e)
        {
            _isShowPopup = false;
        }

        void videoCanvas_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            _isSelectedCanvas = sender as Canvas;
            _isShowPopup = true;
            _ctlPopupVideo.Placement = PlacementMode.Mouse;
            _ctlPopupVideo.IsOpen = true;

        }


        void solutionButton_Click(object sender, RoutedEventArgs e)
        {
            Grid button = sender as Grid;
            _selectGrid = button;
            Datas.Solution solution = button.DataContext as Datas.Solution;
            List<SolutionVideoMatrix> solutionVideoMatrixs = new List<SolutionVideoMatrix>();
            if (solution != null && solution.Mapping != null)
            {

                solution.Clicks = solution.Clicks + 1;
                VMSolutionUntil.UpdateSolution(solution);
                if (_ListVideos != null)
                {
                    LoadVideoMatrix();

                    foreach (Mapping mapp in solution.Mapping)
                    {
                        foreach (Canvas canvas in _ListVideos)
                        {
                            if (canvas != null && canvas.DataContext != null)
                            {
                                Item videoItem = canvas.DataContext as Item;
                                if (videoItem.Id == mapp.VideoSourceId)
                                {
                                    foreach (Canvas matrixCanvas in this._ctlWrapMatrixs.Children)
                                    {
                                        if (matrixCanvas != null && matrixCanvas.DataContext != null)
                                        {
                                            VideoMatrixItem matrixItem = matrixCanvas.DataContext as VideoMatrixItem;
                                            if (matrixItem.Id == mapp.VideoMatrixId && videoItem.Id == mapp.VideoSourceId)
                                            {

                                                SolutionVideoMatrix solutionVideoMatrix = new SolutionVideoMatrix();
                                                solutionVideoMatrix.Item = videoItem;
                                                solutionVideoMatrix.VideoMatrixItem = matrixItem;
                                                solutionVideoMatrixs.Add(solutionVideoMatrix);

                                                string xaml = System.Windows.Markup.XamlWriter.Save(canvas);
                                                Canvas nCanvas = System.Windows.Markup.XamlReader.Parse(xaml) as Canvas;
                                                nCanvas.HorizontalAlignment = System.Windows.HorizontalAlignment.Center;
                                                nCanvas.VerticalAlignment = System.Windows.VerticalAlignment.Center;
                                                //nCanvas.MouseRightButtonDown += videoCanvas_MouseRightButtonDown;
                                                nCanvas.PreviewMouseMove += nCanvas_PreviewMouseMove;
                                                nCanvas.MouseLeftButtonUp += onCanvas_MouseLeftButtonUp;
                                                nCanvas.DataContext = videoItem;
                                                Canvas.SetLeft(nCanvas, (this.ActualWidth * 0.154d - 132) / 2);
                                                Canvas.SetTop(nCanvas, (this.ActualHeight * 0.15 - 85) / 2);
                                                matrixCanvas.Children.Add(nCanvas);
                                                break;
                                            }

                                        }
                                    }
                                    break;
                                }

                            }
                        }


                    }
                }
            }
            SetSolutionButtonBgImage(button);
            if (solutionVideoMatrixs != null)
            {
                foreach (SolutionVideoMatrix solutionVideoMatrix in solutionVideoMatrixs)
                {
                    SendToTarget(solutionVideoMatrix.Item, solutionVideoMatrix.VideoMatrixItem);
                }
                solutionVideoMatrixs.Clear();
            }
        }

        void matrixCanvas_Drop(object sender, DragEventArgs e)
        {
            IDataObject data = e.Data;

            if (data.GetDataPresent(typeof(Canvas)))
            {
                Canvas matrixCanvas = sender as Canvas;
                Canvas rect = data.GetData(typeof(Canvas)) as Canvas;
                string xaml = System.Windows.Markup.XamlWriter.Save(rect);
                string oxaml = string.Empty;
                Canvas omatrixCanvas = new Canvas();
                if (matrixCanvas.Children.Count > 2 && matrixCanvas.Children[2] != null)
                {
                    omatrixCanvas = matrixCanvas.Children[2] as Canvas;
                    if (((matrixCanvas.Children[2] as Canvas).DataContext as Item) != null)
                    {

                        omatrixCanvas.DataContext = (matrixCanvas.Children[2] as Canvas).DataContext as Item;
                    }
                    oxaml = System.Windows.Markup.XamlWriter.Save(matrixCanvas.Children[2]);
                }





                if (matrixCanvas.Children.Count > 2 && matrixCanvas.Children[2] != null)
                {
                    int count = matrixCanvas.Children.Count;

                    for (int i = 0; i < count - 2; i++)
                    {
                        matrixCanvas.Children.RemoveAt(2);
                    }
                }
                if (_isExChange)
                {
                    Canvas pCanvas = rect.Parent as Canvas;

                    if (pCanvas != null && pCanvas.Children.Count > 2 && pCanvas.Children[2] != null)
                    {
                        int count = pCanvas.Children.Count;

                        for (int i = 0; i < count - 2; i++)
                        {
                            pCanvas.Children.RemoveAt(2);
                        }
                    }
                    if (!string.IsNullOrEmpty(oxaml) && pCanvas != null)
                    {
                        Canvas onCanvas = System.Windows.Markup.XamlReader.Parse(oxaml) as Canvas;
                        //onCanvas.DataContext = matrixCanvas.DataContext as VideoMatrixItem;
                        //onCanvas.MouseRightButtonDown += videoCanvas_MouseRightButtonDown;
                        onCanvas.PreviewMouseMove += nCanvas_PreviewMouseMove;
                        onCanvas.DataContext = omatrixCanvas.DataContext as Item;
                        Canvas.SetLeft(onCanvas, (this.ActualWidth * 0.154d - 132) / 2);
                        Canvas.SetTop(onCanvas, (this.ActualHeight * 0.15 - 85) / 2);
                        onCanvas.MouseLeftButtonUp += onCanvas_MouseLeftButtonUp;
                        pCanvas.Children.Add(onCanvas);


                        SendToTarget(omatrixCanvas.DataContext as Item, pCanvas.DataContext as VideoMatrixItem);

                        _isExChange = false;
                    }

                }

                Canvas nCanvas = System.Windows.Markup.XamlReader.Parse(xaml) as Canvas;
                if (rect.DataContext as Item != null)
                {
                    nCanvas.DataContext = rect.DataContext as Item;
                }
                //nCanvas.MouseRightButtonDown += videoCanvas_MouseRightButtonDown;
                nCanvas.PreviewMouseMove += nCanvas_PreviewMouseMove;
                nCanvas.MouseLeftButtonUp += onCanvas_MouseLeftButtonUp;
                Canvas.SetLeft(nCanvas, (this.ActualWidth * 0.154d - 132) / 2);
                Canvas.SetTop(nCanvas, (this.ActualHeight * 0.15 - 85) / 2);
                matrixCanvas.Children.Add(nCanvas);


                SendToTarget(rect.DataContext as Item, matrixCanvas.DataContext as VideoMatrixItem);

            }
        }

        void onCanvas_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            _isShowPopup = true;
            _ctlSelectedStackPanleMatrixs.Children.Clear();
            _selectedMatrixCanvas = sender as Canvas;
            Canvas matrixCanvas = _selectedMatrixCanvas.Parent as Canvas;
            VideoMatrixItem matrixItem = matrixCanvas.DataContext as VideoMatrixItem;
            List<VideoMatrixItem> listVideos = VMSolutionUntil.GetListVideoMatrixSource(VMSolutionUntil.GetVideoMatrixFilePath(), "VideoMatrix");

            foreach (VideoMatrixItem item in listVideos)
            {
                if (matrixItem.Id == item.Id)
                {
                    listVideos.Remove(item);
                    break;
                }
            }

            for (int i = 0; i < listVideos.Count; i++)
            {
                Button matrixbtn = new Button();
                matrixbtn.Height = 44;
                matrixbtn.Click += matrixbtn_Click;
                matrixbtn.DataContext = listVideos[i];
                matrixbtn.Content = listVideos[i].Caption;
                _ctlSelectedStackPanleMatrixs.Children.Add(matrixbtn);

            }
            _ctlPopupMatrix.Placement = PlacementMode.Mouse;
            _ctlPopupMatrix.IsOpen = true;

        }

        void matrixbtn_Click(object sender, RoutedEventArgs e)
        {
            string oxaml = string.Empty;
            Canvas omatrixCanvas = new Canvas();

            //_selectedMatrixCanvas要移动的视频源
            if (_selectedMatrixCanvas != null)
            {

                Item selectedMatrixItem = _selectedMatrixCanvas.DataContext as Item;
                Button matrixButton = sender as Button;
                //selectedMatrixCanvas要移动的目标矩阵
                VideoMatrixItem matrixItem = matrixButton.DataContext as VideoMatrixItem;

                foreach (UIElement ui in _ctlWrapMatrixs.Children)
                {
                    Canvas matrixCanvas = ui as Canvas;
                    if ((matrixCanvas.DataContext as VideoMatrixItem).Id == matrixItem.Id)
                    {
                        if (matrixCanvas.Children.Count > 2 && matrixCanvas.Children[2] != null)
                        {
                            omatrixCanvas = matrixCanvas.Children[2] as Canvas;
                            omatrixCanvas.DataContext = (matrixCanvas.Children[2] as Canvas).DataContext as Item;
                            oxaml = System.Windows.Markup.XamlWriter.Save(matrixCanvas.Children[2]);
                        }
                        if (matrixCanvas.Children.Count > 2 && matrixCanvas.Children[2] != null)
                        {
                            int count = matrixCanvas.Children.Count;

                            for (int i = 0; i < count - 2; i++)
                            {
                                matrixCanvas.Children.RemoveAt(2);
                            }
                        }
                        string xaml = System.Windows.Markup.XamlWriter.Save(_selectedMatrixCanvas);
                        Canvas nCanvas = System.Windows.Markup.XamlReader.Parse(xaml) as Canvas;
                        nCanvas.DataContext = _selectedMatrixCanvas.DataContext as Item;
                        //nCanvas.MouseRightButtonDown += videoCanvas_MouseRightButtonDown;
                        nCanvas.PreviewMouseMove += nCanvas_PreviewMouseMove;
                        nCanvas.MouseLeftButtonUp += onCanvas_MouseLeftButtonUp;
                        Canvas.SetLeft(nCanvas, (this.ActualWidth * 0.154d - 132) / 2);
                        Canvas.SetTop(nCanvas, (this.ActualHeight * 0.15 - 85) / 2);
                        matrixCanvas.Children.Add(nCanvas);

                        ////发送视频切换指令
                        //Solution osolution = new Solution();
                        //osolution.Mapping = new List<Mapping>();
                        //Mapping omapping = new Mapping();
                        //omapping.VideoMatrixId = matrixItem.Id;

                        //omapping.VideoSourceId = (_selectedMatrixCanvas.DataContext as Item).Id;
                        //osolution.Mapping.Add(omapping);

                        //string otargetIP = System.Configuration.ConfigurationManager.AppSettings["TargetIP"];
                        //int otargetPort = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["TargetPort"]);
                        //// 发送到agent程序，让agent程序转发
                        //Untils.VMAgentUtil.SendToAgent(otargetIP, otargetPort, osolution);

                        SendToTarget(_selectedMatrixCanvas.DataContext as Item, matrixItem);
                        break;
                    }
                }
            }

            Canvas oMatrixCanvas = _selectedMatrixCanvas.Parent as Canvas;
            if (oMatrixCanvas.Children.Count > 2 && oMatrixCanvas.Children[2] != null)
            {
                int count = oMatrixCanvas.Children.Count;

                for (int i = 0; i < count - 2; i++)
                {
                    oMatrixCanvas.Children.RemoveAt(2);
                }
            }
            if (!string.IsNullOrEmpty(oxaml))
            {
                Canvas oCanvas = System.Windows.Markup.XamlReader.Parse(oxaml) as Canvas;
                oCanvas.DataContext = omatrixCanvas.DataContext as Item;
                //oCanvas.MouseRightButtonDown += videoCanvas_MouseRightButtonDown;
                oCanvas.PreviewMouseMove += nCanvas_PreviewMouseMove;
                oCanvas.MouseLeftButtonUp += onCanvas_MouseLeftButtonUp;
                Canvas.SetLeft(oCanvas, (this.ActualWidth * 0.154d - 132) / 2);
                Canvas.SetTop(oCanvas, (this.ActualHeight * 0.15 - 85) / 2);
                oMatrixCanvas.Children.Add(oCanvas);

                //////发送视频切换指令
                //Solution solution = new Solution();
                //solution.Mapping = new List<Mapping>();
                //Mapping mapping = new Mapping();
                //mapping.VideoMatrixId = (oMatrixCanvas.DataContext as VideoMatrixItem).Id;
                //mapping.VideoSourceId = (oCanvas.DataContext as Item).Id;
                //solution.Mapping.Add(mapping);

                //string targetIP = System.Configuration.ConfigurationManager.AppSettings["TargetIP"];
                //int targetPort = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["TargetPort"]);
                //// 发送到agent程序，让agent程序转发
                //Untils.VMAgentUtil.SendToAgent(targetIP, targetPort, solution);

                SendToTarget(oCanvas.DataContext as Item, oMatrixCanvas.DataContext as VideoMatrixItem);
            }

            _ctlPopupMatrix.IsOpen = false;
        }

        void matrixCanvas_DragOver(object sender, DragEventArgs e)
        {
            if (!e.Data.GetDataPresent(typeof(Canvas)))
            {
                e.Effects = DragDropEffects.None;
                e.Handled = true;
                _isShowPopup = false;
            }
        }

        //void videoCanvas_MouseRightButtonDown(object sender, MouseButtonEventArgs e)
        //{
        //    Canvas oCanvas = sender as Canvas;
        //    Canvas pCanvas = oCanvas.Parent as Canvas;
        //    Item pItem = new Item();
        //    if (pCanvas != null && pCanvas.DataContext != null)
        //    {
        //        pItem = pCanvas.DataContext as Item;
        //    }
        //    if (oCanvas != null && oCanvas.DataContext != null)
        //    {
        //        Item item = oCanvas.DataContext as Item;

        //        if (_ctlWrapMatrixs.Children != null)
        //        {

        //            foreach (Canvas nCanvas in _ctlWrapMatrixs.Children)
        //            {
        //                if (nCanvas != null && nCanvas.DataContext != null)
        //                {
        //                    Item matrixItem = nCanvas.DataContext as Item;
        //                    if (nCanvas.Children.Count > 2)
        //                    {
        //                        if (nCanvas.Children[2] != null)
        //                        {
        //                            Canvas videoCanvas = nCanvas.Children[2] as Canvas;
        //                            if (videoCanvas != null && videoCanvas.DataContext != null)
        //                            {
        //                                Item videoItem = videoCanvas.DataContext as Item;
        //                                if (videoItem.Id == item.Id && pItem.Id == matrixItem.Id)
        //                                {
        //                                    nCanvas.Children.Remove(videoCanvas);
        //                                    break;
        //                                }
        //                            }
        //                        }
        //                    }
        //                }
        //            }
        //        }
        //    }
        //}

        void videoCanvas_PreviewMouseMove(object sender, MouseEventArgs e)
        {
            if (e.LeftButton == MouseButtonState.Pressed && !_isShowPopup)
            {
                this.StartDrag(sender, e);
            }
        }

        private void StartDrag(object sender, MouseEventArgs e)
        {
            Canvas canvas = sender as Canvas;
            this._dragScope = Application.Current.MainWindow.Content as FrameworkElement;

            this._dragScope.AllowDrop = true;

            DragEventHandler draghandler = new DragEventHandler(DragScope_PreviewDragOver);
            this._dragScope.PreviewDragOver += draghandler;
            _dragScopeasVisual = canvas;
            this._adorner = new DragAdorner(this._dragScope, (UIElement)canvas, 0.5);
            this._layer = AdornerLayer.GetAdornerLayer(this._dragScope as Visual);
            this._layer.Add(this._adorner);

            DataObject data = new DataObject(typeof(Canvas), canvas);
            DragDrop.DoDragDrop(canvas, data, DragDropEffects.Move);

            AdornerLayer.GetAdornerLayer(this._dragScope).Remove(this._adorner);
            this._adorner = null;

            this._dragScope.PreviewDragOver -= draghandler;

        }

        void DragScope_PreviewDragOver(object sender, DragEventArgs args)
        {
            if (this._adorner != null)
            {
                this._adorner.LeftOffset = args.GetPosition(this._dragScope).X;
                this._adorner.TopOffset = args.GetPosition(this._dragScope).Y;
            }

        }

        private void _ctlBtnSave_Click(object sender, RoutedEventArgs e)
        {
            SaveSolutionConfigWindow saveSolutionConfigWindow = new SaveSolutionConfigWindow(_numberCount);
            if (saveSolutionConfigWindow.ShowDialog() == true)
            {
                Solution solution = new Solution();
                solution.Name = saveSolutionConfigWindow.SaveName;
                solution.Caption = "";
                solution.Sortid = saveSolutionConfigWindow.saveSort;
                solution.Number = saveSolutionConfigWindow.SaveNumber;
                solution.Clicks = 0;
                solution.Mapping = new List<Mapping>();
                foreach (Canvas child in this._ctlWrapMatrixs.Children)
                {
                    if (child.DataContext != null)
                    {
                        Item matrixItem = child.DataContext as Item;
                        Mapping mapping = new Mapping();
                        mapping.VideoMatrixId = matrixItem.Id;
                        if (child.Children.Count > 2)
                        {
                            Canvas canvas = child.Children[2] as Canvas;
                            if (canvas != null && canvas.DataContext != null)
                            {
                                Item videoItem = canvas.DataContext as Item;
                                mapping.Type = videoItem.Type;
                                solution.Mapping.Add(mapping);
                            }
                        }
                    }

                }

                //执行添加xml信息
                if (VMSolutionUntil.AddSolution(solution))
                {
                    MessageBox.Show("添加信息成功！");
                    LoadSolutionConfig(null);
                }
                else
                {
                    MessageBox.Show("添加信息失败！");
                }
            }
        }

        private void LoadSorts()
        {
            List<Datas.Sort> sorts = VMSolutionUntil.GetSorts(false);
            if (sorts != null)
            {
                _ctlStackPanelSorts.Children.Clear();
                for (int i = 0; i < sorts.Count; i++)
                {
                    MenuItem item = new MenuItem();
                    //item.Foreground = new SolidColorBrush(Colors.Black);
                    //item.Height = 40;
                    //item.Width = 188;
                    //ImageBrush imageBrush = new ImageBrush();

                    //imageBrush.ImageSource = new BitmapImage(new Uri("Images/topbon50px.png", UriKind.Relative));
                    //item.Background = imageBrush;
                    if (i == 0)
                    {
                        item.Style = (Style)Window.Resources["selectMenuItem"];
                    }
                    else
                    {
                        item.Style = (Style)Window.Resources["menuItem"];
                    }
                    item.DataContext = sorts[i];
                    item.Click += item_Click;
                    item.Tag = sorts[i].Id.ToString();
                    TextBlock textBlock = new TextBlock();
                    textBlock.Text = sorts[i].Caption;
                    textBlock.FontSize = 15;
                    textBlock.HorizontalAlignment = System.Windows.HorizontalAlignment.Center;
                    textBlock.VerticalAlignment = System.Windows.VerticalAlignment.Center;
                    item.Header = textBlock;
                    _ctlStackPanelSorts.Children.Add(item);
                }
            }
        }

        void item_Click(object sender, RoutedEventArgs e)
        {
            MenuItem menuItem = sender as MenuItem;
            if (menuItem != null && menuItem.DataContext != null)
            {
                Sort sort = menuItem.DataContext as Sort;
                _ctlTxtBlockState.Content = sort.Caption;

                if (sort.Id == 0)
                {
                    LoadSolutionConfig(null);
                    LoadVideoSource(null);
                }
                else
                {
                    LoadSolutionConfig(VMSolutionUntil.GetListSolutionBySortid(sort.Id.ToString()));
                    LoadVideoSource(VMSolutionUntil.GetListVideoBySortId(VMSolutionUntil.GetVideoSourceFilePath(), sort.Id.ToString()));
                }
                SetMenuItemBgIamge(menuItem);
            }
        }

        private void _ctlTabItemSolutions_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            LoadSolutionConfig(null);
        }

        private void _ctlTabItemVideos_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            LoadVideoSource(null);
        }


        void saveSolutionConfigWindow_Closed(object sender, EventArgs e)
        {
            Button resSp = _stackPanel.Children[0] as Button;
            resSp.Style = (Style)Window.Resources["gdFunc"];
        }


        private void SetNavButBgImage(Button gd)
        {
            if (_stackPanel.Children[0] != null)
            {
                Button resSp = _stackPanel.Children[0] as Button;
                resSp.Style = (Style)Window.Resources["gdSelectFunc"];
            }

        }


        private void SetMenuItemBgIamge(MenuItem mi)
        {
            foreach (UIElement element in _ctlStackPanelSorts.Children)
            {
                if (element is MenuItem)
                {
                    MenuItem item = element as MenuItem;
                    if (item.Tag.ToString().Equals(mi.Tag.ToString()))
                    {
                        item.Style = (Style)Window.Resources["selectMenuItem"];
                    }
                    else
                    {
                        item.Style = (Style)Window.Resources["menuItem"];
                    }
                }
            }
        }

        private void SetSolutionButtonBgImage(Grid gd)
        {
            foreach (UIElement element in _ctlWplSolutions.Children)
            {
                if (element is Grid)
                {
                    Grid grid = element as Grid;
                    if (grid.Tag.ToString().Equals(gd.Tag.ToString()))
                    {
                        grid.Style = (Style)Window.Resources["selectSolutionButton"];
                    }
                    else
                    {
                        grid.Style = (Style)Window.Resources["solutionButton"];
                    }
                }
            }
        }



        private void _ctlBtnNumber_MouseLeftButtonDown_1(object sender, MouseButtonEventArgs e)
        {
            if (_selectedRadioButtonSolution)
            {
                isOrderBy = _isOrderBy;
                _ctlBtnNumber.Style = (Style)Window.Resources["selectSort"];
                _ctlBtnFrequency.Style = (Style)Window.Resources["sort"];

                List<Solution> ListSolution = VMSolutionUntil.GetAllSolution();
                if (isOrderBy)
                {
                    _ctlLblNumber.Content = "按序号↑";
                    var solutions = ListSolution.OrderBy(solution => solution.Number);
                    _isOrderBy = false;
                    List<Solution> nListSolution = new List<Solution>();
                    foreach (var solution in solutions)
                    {
                        Solution osolution = solution as Solution;
                        nListSolution.Add(osolution);
                    }
                    LoadSolutionConfig(nListSolution);
                }
                else
                {
                    _ctlLblNumber.Content = "按序号↓";
                    var solutions = ListSolution.OrderByDescending(solution => solution.Number);
                    _isOrderBy = true;
                    List<Solution> nListSolution = new List<Solution>();
                    foreach (var solution in solutions)
                    {
                        Solution osolution = solution as Solution;
                        nListSolution.Add(osolution);
                    }
                    LoadSolutionConfig(nListSolution);
                }
            }
            else if (_selectedRadioButtonItem)
            {
                isFrequency = _isFrequency;
                _ctlBtnNumber.Style = (Style)Window.Resources["selectSort"];
                _ctlBtnFrequency.Style = (Style)Window.Resources["sort"];

                List<Item> Items = VMSolutionUntil.GetListVideoSource(VMSolutionUntil.GetVideoSourceFilePath(), "VideoSource");
                if (isFrequency)
                {
                    _ctlLblNumber.Content = "按序号↑";

                    var solutions = Items.OrderBy(solution => solution.Number);
                    List<Item> nListSolution = new List<Item>();
                    foreach (var solution in solutions)
                    {
                        Item osolution = solution as Item;
                        nListSolution.Add(osolution);
                    }
                    LoadVideoSource(nListSolution);
                    //LoadSolutionConfig(nListSolution);

                    _isFrequency = false;
                }
                else
                {
                    _ctlLblNumber.Content = "按序号↓";
                    var solutions = Items.OrderByDescending(solution => solution.Number);
                    _isFrequency = true;
                    List<Item> nListSolution = new List<Item>();
                    foreach (var solution in solutions)
                    {
                        Item osolution = solution as Item;
                        nListSolution.Add(osolution);
                    }
                    LoadVideoSource(nListSolution);
                }
            }
           
        
        }

        private void _ctlBtnFrequency_MouseLeftButtonDown_1(object sender, MouseButtonEventArgs e)
        {

            if (_selectedRadioButtonSolution)
            {
                isFrequency = _isFrequency;
                _ctlBtnFrequency.Style = (Style)Window.Resources["selectSort"];
                _ctlBtnNumber.Style = (Style)Window.Resources["sort"];
             

                List<Solution> ListSolution = VMSolutionUntil.GetAllSolution();
                if (isFrequency)
                {
                    _ctlLblFrequency.Content = "按使用频率↑";

                    var solutions = ListSolution.OrderBy(solution => solution.Clicks);
                    List<Solution> nListSolution = new List<Solution>();
                    foreach (var solution in solutions)
                    {
                        Solution osolution = solution as Solution;
                        nListSolution.Add(osolution);
                    }
                    LoadSolutionConfig(nListSolution);
                    _isFrequency = false;
                }
                else
                {
                    _ctlLblFrequency.Content = "按使用频率↓";
                    var solutions = ListSolution.OrderByDescending(solution => solution.Clicks);
                    _isFrequency = true;
                    List<Solution> nListSolution = new List<Solution>();
                    foreach (var solution in solutions)
                    {
                        Solution osolution = solution as Solution;
                        nListSolution.Add(osolution);
                    }
                    LoadSolutionConfig(nListSolution);
                }
            }
            else if (_selectedRadioButtonItem)
            {
                isFrequency = _isFrequency;
                _ctlBtnFrequency.Style = (Style)Window.Resources["selectSort"];
                _ctlBtnNumber.Style = (Style)Window.Resources["sort"];
             

                List<Item> Items = VMSolutionUntil.GetListVideoSource(VMSolutionUntil.GetVideoSourceFilePath(), "VideoSource");
                if (isFrequency)
                {
                    _ctlLblFrequency.Content = "按使用频率↑";

                    var solutions = Items.OrderBy(solution => solution.Clicks);
                    List<Item> nListSolution = new List<Item>();
                    foreach (var solution in solutions)
                    {
                        Item osolution = solution as Item;
                        nListSolution.Add(osolution);
                    }
                    LoadVideoSource(nListSolution);
                    //LoadSolutionConfig(nListSolution);
                    _isFrequency = false;
                }
                else
                {
                    _ctlLblFrequency.Content = "按使用频率↓";
                    var solutions = Items.OrderByDescending(solution => solution.Clicks);
                    _isFrequency = true;
                    List<Item> nListSolution = new List<Item>();
                    foreach (var solution in solutions)
                    {
                        Item osolution = solution as Item;
                        nListSolution.Add(osolution);
                    }
                    LoadVideoSource(nListSolution);
                }
            }

        }

        private void spFunction_Click_1(object sender, RoutedEventArgs e)
        {
            SetNavButBgImage(spFunction);

            SaveSolutionConfigWindow saveSolutionConfigWindow = new SaveSolutionConfigWindow(_numberCount);
            saveSolutionConfigWindow.Closed += saveSolutionConfigWindow_Closed;
            if (saveSolutionConfigWindow.ShowDialog() == true)
            {
                Solution solution = new Solution();
                solution.Name = saveSolutionConfigWindow.SaveName;
                solution.Caption = "";
                solution.Sortid = saveSolutionConfigWindow.saveSort;
                solution.Number = saveSolutionConfigWindow.SaveNumber;
                solution.Clicks = 0;
                solution.Mapping = new List<Mapping>();
                foreach (Canvas child in this._ctlWrapMatrixs.Children)
                {
                    if (child.DataContext != null)
                    {
                        VideoMatrixItem matrixItem = child.DataContext as VideoMatrixItem;
                        Mapping mapping = new Mapping();
                        mapping.VideoMatrixId = matrixItem.Id;
                        if (child.Children.Count > 2)
                        {
                            Canvas canvas = child.Children[2] as Canvas;
                            if (canvas != null && canvas.DataContext != null)
                            {
                                Item videoItem = canvas.DataContext as Item;
                                mapping.VideoSourceId = videoItem.Id;
                                mapping.Type = videoItem.Type;
                                solution.Mapping.Add(mapping);
                            }
                        }
                    }

                }

                //执行添加xml信息
                if (VMSolutionUntil.AddSolution(solution))
                {
                    MessageBox.Show("添加信息成功！");

                    LoadSolutionConfig(VMSolutionUntil.GetListSolutionBySortid(solution.Sortid.ToString()));
                    LoadVideoSource(VMSolutionUntil.GetListVideoBySortId(VMSolutionUntil.GetVideoSourceFilePath(), solution.Sortid.ToString()));


                    foreach (UIElement element in _ctlStackPanelSorts.Children)
                    {
                        if (element is MenuItem)
                        {
                            MenuItem item = element as MenuItem;
                            if (item.Tag.ToString().Equals(solution.Sortid.ToString()))
                            {
                                item.Style = (Style)Window.Resources["selectMenuItem"];
                            }
                            else
                            {
                                item.Style = (Style)Window.Resources["menuItem"];
                            }
                        }
                    }

                }
                else
                {
                    MessageBox.Show("添加信息失败！");
                }

            }
        }

        private void RadioButton_Click_1(object sender, RoutedEventArgs e)
        {
            _selectedRadioButtonSolution = true;
            _selectedRadioButtonItem = false;
            //LoadVideoSource(null);
            _ctlScrollViewerVideos.Visibility = System.Windows.Visibility.Collapsed;
            _ctlScrollViewerSolutions.Visibility = System.Windows.Visibility.Visible;
        }

        private void RadioButton_Click_2(object sender, RoutedEventArgs e)
        {
            _selectedRadioButtonSolution = false;
            _selectedRadioButtonItem = true;
            // LoadSolutionConfig(null);
            _ctlScrollViewerVideos.Visibility = System.Windows.Visibility.Visible;
            _ctlScrollViewerSolutions.Visibility = System.Windows.Visibility.Collapsed;
        }

        private void _ctlPopupMatrix_Closed_1(object sender, EventArgs e)
        {
            _isDeleteSolution = false;
        }

        private void _ctlBtnDeleteSolution_Click_1(object sender, RoutedEventArgs e)
        {
            if (_selectGrid != null)
            {
                Solution solution = _selectGrid.DataContext as Solution;
                if (VMSolutionUntil.DeleteSolution(solution))
                {
                    LoadSolutionConfig(null);
                }
            }
        }

        /// <summary>
        /// 关闭
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Button_Click(object sender, RoutedEventArgs e)
        {
            Application.Current.Shutdown();
        }
    }
}
